package com.himiotech.core.framework.helper.aspect;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.himiotech.core.framework.config.async.AsyncFactory;
import com.himiotech.core.framework.config.async.AsyncManager;
import com.himiotech.core.framework.helper.anno.Log;
import com.himiotech.core.framework.helper.enums.BusinessStatus;
import com.himiotech.core.framework.helper.exception.HimioException;
import com.himiotech.core.framework.helper.utils.ServletUtils;
import com.himiotech.core.framework.helper.utils.ShiroUtils;
import com.himiotech.core.project.model.entity.OperateLog;
import com.himiotech.core.project.model.entity.user.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 操作日志记录处理
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    /**
     * 排除敏感属性字段
     */
    public static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"};

    /**
     * 配置织入点
     */
    @Pointcut("@annotation(com.himiotech.core.framework.helper.anno.Log)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        try {
            handleLog(joinPoint, null, jsonResult);
        } catch (Exception e) {
            throw new HimioException(e.getMessage());
        }
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            // 获取当前的用户
            User currentUser = ShiroUtils.getSysUser();

            // *========数据库日志=========*//
            OperateLog operateLog = new OperateLog();
            operateLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            // 请求的地址
            String ip = ShiroUtils.getIp();
            operateLog.setOperateIp(ip);
            // 返回参数
            if (ObjectUtil.isNotNull(jsonResult)) {
                operateLog.setJsonResult(StringUtils.substring(JSONUtil.toJsonStr(jsonResult), 0, 2000));
            }

            operateLog.setOperateUrl(ServletUtils.getRequest().getRequestURI());
            if (currentUser != null) {
                operateLog.setOperateName(currentUser.getLoginName());
                if (currentUser.getDept() != null
                        && StringUtils.isNotEmpty(currentUser.getDept().getDeptName())) {
                    operateLog.setDeptName(currentUser.getDept().getDeptName());
                }
            }

            if (e != null) {
                operateLog.setStatus(BusinessStatus.FAIL.ordinal());
                operateLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operateLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operateLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(controllerLog, operateLog);
            // 保存数据库
            AsyncManager.me().execute(AsyncFactory.recordOperateLog(operateLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log        日志
     * @param operateLog 操作日志
     */
    public void getControllerMethodDescription(Log log, OperateLog operateLog) {
        // 设置action动作
        operateLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operateLog.setTitle(log.title());
        // 设置操作人类别
        operateLog.setOperateType(log.operatorType().ordinal());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(operateLog);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operateLog
     */
    private void setRequestValue(OperateLog operateLog) {
        Map<String, String[]> map = new HashMap<>(ServletUtils.getRequest().getParameterMap());
        if (MapUtil.isNotEmpty(map)) {
            Arrays.stream(EXCLUDE_PROPERTIES).forEach(map::remove);
            String params = JSONUtil.toJsonStr(map);
            operateLog.setOperateParam(StringUtils.substring(params, 0, 2000));
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }
}
